package com.westos.todo.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.apache.ibatis.session.SqlSession;

import com.westos.todo.dao.TodoDAO;
import com.westos.todo.entity.Todo;
import com.westos.todo.entity.TodoClass;
import com.westos.todo.page.TodoClassVO;
import com.westos.todo.services.TodoService;
import com.westos.todo.utils.MybatisUtil;

public class TodoServiceImpl implements TodoService {

	@Override
	public List<TodoClassVO> listTodoClasses(Integer parentid) {
		SqlSession sqlSession = MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDAO dao = sqlSession.getMapper(TodoDAO.class);
		List<TodoClassVO> result = new ArrayList<>();
		try {
			List<TodoClass> root = dao.listTodoClassesByParentid(parentid);
			
			for (TodoClass tc : root) {
				TodoClassVO todoClassVO = new TodoClassVO();
				todoClassVO.setTodoclass(tc);
				todoClassVO.setTodos(dao.listTodosByClassid(tc.getId()));
				todoClassVO.setTodoclassvolist(listTodoClasses(tc.getId()));
				result.add(todoClassVO);
			}
			return result;
		} finally {
			sqlSession.close();
		}
	}

	@Override
	public boolean saveTodoClass(TodoClass todoClass) {
			SqlSession sqlSession = MybatisUtil.getInstance().getSqlSessionFactory().openSession();
			TodoDAO dao = sqlSession.getMapper(TodoDAO.class);
			int result=0;
			try {
				result=dao.saveTodoClass(todoClass);
				sqlSession.commit();
			} finally {
				sqlSession.close();
			}
			return result>0;
	}

	

	@Override
	public boolean saveTodo(Todo todo) {
		SqlSession sqlSession = MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDAO dao = sqlSession.getMapper(TodoDAO.class);
		int result=0;
		try {
			result = dao.saveTodo(todo);
			sqlSession.commit();
		} finally {
			sqlSession.close();
		}
		return result>0;
	}

	

	@Override
	public Boolean updataTodo(Integer id) {
		SqlSession sqlSession=MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDAO dao = sqlSession.getMapper(TodoDAO.class);
		int result=0;
		try {
			result = dao.updateTodoState(id);
			sqlSession.commit();
		} finally {
			sqlSession .close();
		}
		return result>0;
	}

	@Override
	public boolean removeTodo(Integer id) {
		SqlSession sqlSession=MybatisUtil.getInstance().getSqlSessionFactory().openSession();
		TodoDAO dao = sqlSession.getMapper(TodoDAO.class);
		int result=0;
		
		try {
			result=dao.removeTodo(id);
			sqlSession.commit();
		} finally{
			sqlSession.close();
		}
		
		return result>0;
	}

}
